# -*- encoding:utf-8 -*-
# !/usr/bin/env python

# @Description: 每天00：00根据数据库配置删除操作日志
# @Author: DaiJin(1186567548@qq.com)


# parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.insert(0, parentdir)
from psycopg2 import connect
from psycopg2.extras import RealDictCursor

import json
import schedule
import time
import logging
import traceback


def loadCONF(path, sysPath="/opt/sap/conf/sap.ini"):
    """
    arguments:
    @param: sysPath 生产环境配置文件默认位置
    @param: path 开发环境，指定配置文件路径
    @return: dict, 详细配置
    """
    import platform
    import configparser as cp
    from cencrypt.cencrypt import cencrypt
    
    configPath = sysPath
    if "Windows" == platform.system() or "Darwin" == platform.system():
        configPath = path
    cf = cp.ConfigParser()
    ec = cencrypt()
    with open(configPath) as f:
        f_content = f.read()
    data = unicode(ec.decryptionstr(f_content), "utf-8")
    cf.read_string(data)
    sets = cf.sections()
    conf = {}
    for key in sets:
        conf[key] = {}
        vals = cf.items(key)
        for val in vals:   
            conf[key][val[0]] = val[1]
    return conf


filepath = "../sap.ini"
conf = loadCONF(filepath)


class DatabaseConfig(object):
    siem = json.loads(conf.get('SAP-API').get('pg_conn'))
    ES_ADDR = conf.get('SAP-API').get('es')


# 设置log, 这里使用默认log
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='[%Y-%m_%d %H:%M:%S]',
                    # filename=os.path.dirname(os.path.realpath(__file__)) + "/" + u'删除任务错误信息.txt',
                    filename=("../log/操作日志异常信息.txt"),
                    filemode='a')


# 每天00：00根据数据库配置删除操作日志
def deletelog():
    conn = connect(**DatabaseConfig.siem)  # 链接数据库
    cur = conn.cursor(cursor_factory=RealDictCursor)
    try:
        cur.execute("""select deadline from h_operate_log_deadline where deadline_id = 1""")
        deadline = cur.fetchone()['deadline']
        cur.execute("""delete from sys_operate_log where operate_time < now() - interval '%s %s'""" % (deadline[:1], deadline[2:]))
        # print (deadline)
        # print 'success'
    except Exception:
        # format_exc()返回字符串，print_exc()则直接给打印出来
        traceback.print_exc()
        logging.warning("except, failed msg:\n" + traceback.format_exc())
    conn.commit()  # 提交
    cur.close()    # 关闭游标
    conn.close()   # 关闭连接


schedule.every().day.at("00:00").do(deletelog)
# schedule.every(1).minutes.do(deletelog)

while True:
    schedule.run_pending()
    time.sleep(1)
